<?php
/**
 * 发仔<i@fazi.me> 2018-07-09
 */
namespace app\open\controller;

use app\open\validate;
use think\Model;
use think\Loader;
class Base extends \app\adminapi\controller\Base
{
    public $session;
    /**
     * 继承原来的adminapi
     */
    public function _initialize()
    {

        parent::_initialize();
        // 验证用户是否登录，以及是否有权限进行操作
//        $this->_session = ( new \app\adminapi\model\User() )->checkAuth();
//        $this->requestMethod = Request::instance()->isPost(); //测试期间允许GET方便测试
//        $this->dateTime = date('Y-m-d H:i:s');
//        $this->uid      = input('uid');
//        if(Request::instance()->isOptions()){
//            $this->cos();
//            exit();
//        }
        $this->cos();
    }

    /**
     * 提取参数（列表）
     */
    protected function getParam($validate = false,$scene = 'list') {
        // 校验请求参数
        if(!$validate) {
            $validate = new validate\CommonValidate();
        }
        // 验证与获取所有请求参数
        $param = $validate->scene($scene)->goCheck()->getCurrentData();

        //列表之外处
        if($scene != 'list') {
            $param = input('param.');
        } else {
            $param['where'] = !empty($param['where_json'] ) ? json_decode($param['where_json'],1) : [];
            $param['fields'] = $param['fields']  ?: '*';
        }

        return $param;
    }

    /**
     * 共用获取总数
     * @param $model
     * @param $joins
     * @return integer count
     */
    protected function getCountCommon(Model $model,$joins = [], $whrerIn = []) {
        //1.参数传入和验证
        $param = $this->getParam();
        //2 过滤
        if($param['with_trashed'] == 1) {
            $model = $model->withTrashed();
        } elseif($param['with_trashed'] == 2) {
            $model = $model->onlyTrashed();
        }
        //分析where
        $this->setJoinWhere($model,$param['where'],$joins);
        //总数
        $count = $model->with($joins)->where($param['where'])->where($whrerIn)->fetchSql(0)->count();
        return $count;
    }

    /**
     * 共用获取列表功能
     * @model string 模型名
     * @joins array 关联
     * @throws
     */
    protected function getListOrAll(Model $model,$joins = [],$keys = [], $whrerIn = [])
    {
        $data = [];
        //1.参数传入和验证
        $param = $this->getParam();
        //2 过滤
        if($param['with_trashed'] == 1) {
            $model = $model->withTrashed();
        } elseif($param['with_trashed'] == 2) {
            $model = $model->onlyTrashed();
        }
        //5. 全部
        $param['is_all'] = $param['is_tree'] ? 1 : $param['is_all'];
        if(!$param['is_all']) {
            $model = $model->page($param['page'])->limit($param['pagenum']);
        }
        //排序
        if($param['sort']) {
            if( in_array(explode(' ',$param['sort'])[0],$model->getTableInfo()['fields']) ) {
                $sort = $param['sort'];
            }
        } else {
            $sort = '`'.$model->getPk().'` DESC';
        }
        //分析where
        $this->setJoinWhere($model,$param['where'],$joins);
        //6. 列表处理
        $list = $model->with($joins)->where($param['where'])->where($whrerIn)->order($sort)->fetchSql(0)->select();
//        halt($list);
        if($list) {
            foreach ($list AS $item) {
                $temp = $item->toArray();#临时变量
                //关联读取数据
                if($joins) {
                    foreach ($joins AS $join) {

                        $temp[$join] = [];
                        if($item->$join) {
                            $temp[$join] = is_array($item->$join) ? $item->$join : $item->$join->toArray();
                        }
//                        $temp[$join] = $item->$join ? $item->$join->toArray() : [];
                    }
                }
                //关联键值
                if($keys) {
                    foreach ($keys AS $key) {
                        $temp[$key] = is_array($item->$key) ? $item->$key : $item->$key->toArray();
                    }
                }
                $data[] = $temp;
            }
        }
        return $data;

    }

    /**
     * 有关联时WHERE键值分析
     * @param Model $model
     * @param array $param
     * @param array $joins
     */
    protected function setJoinWhere($model, &$where = [], $joins = [])
    {
        if(!empty($where)) {
            if($joins) {
                $table = Loader::parseName(basename(str_replace('\\', '/',$model->getModel() )),0,false);
                $field = $model->getTableInfo()['fields'];
                foreach ($where AS $key => $value) {
                    if(in_array($key,$field)) {
                        $where[$table.'.'.$key] = $value;
                        unset($where[$key]);
                    }
                }
            }
        }
    }

    /**
     * 添加共用
     * @return mixed|void
     */
    protected function addCommon(\think\Model $model, $valid = false)
    {

        //1.参数传入和验证
        $param = $this->getParam($valid,'add');
        //是否处理数据
        if(method_exists($model,'parseData')) {
            $param = $model->parseData($param);
        }
        //2. 软删除
        $rslt = $model->allowField(true)->save($param);
        $pk = $model->getPk();
        //3.结果
        return $rslt ? $model->$pk : 0;
    }
    /**
     * 编辑共用
     * @return mixed|void
     */
    protected function editCommon(\think\Model $model, $valid = false)
    {
        //1.参数传入和验证
        $param = $this->getParam($valid,'edit');
        //是否处理数据
        if(method_exists($model,'parseData')) {
            $param = $model->parseData($param);
        }
        //判断编辑方法是否存在
        if( method_exists($model,'edit')) {
            $rslt = $model->edit($param);
        } else {
            //2. 软删除
            $rslt = $model->allowField(true)->isUpdate()->save($param);
        }
        //3.结果
        return $rslt;
    }

    /**
     * 删除共用
     * @return mixed|void
     */
    protected function deleteCommon($model,$validate = false)
    {
        $rslt = false;
        //1.参数传入和验证
        $param = $this->getParam($validate,'delete');
        //2. 软删除
        $data = $model->get($param['ids']);
        if ($data) {
            $rslt = $data->delete();
        }
//        $rslt = $model->get($param['ids'])->delete();
        //3.结果
        return $rslt;
    }

    /**
     * 重写返回[有数据正常，反之亦然]
     * @param array $msgordata
     * @return mixed|void
     */
    protected function res($MsgOrData = [],$data = [])
    {
        $data = $data ?: $MsgOrData;
        if ($data) {
            if(!isset($data['count'])) {
                $data = ['data' => $data];
            }
            return $this->retSucc($data);
        } else {
            return $this->retError($MsgOrData);
        }

    }
}